package cn.cubic.sys.modular.buyrelation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.cubic.core.exception.ServiceException;
import cn.cubic.core.factory.PageFactory;
import cn.cubic.core.pojo.page.PageResult;
import cn.cubic.sys.modular.buyrelation.entity.BuyRelation;
import cn.cubic.sys.modular.buyrelation.mapper.BuyRelationMapper;
import cn.cubic.sys.modular.buyrelation.model.param.BuyRelationParam;
import cn.cubic.sys.modular.buyrelation.service.BuyRelationService;
import cn.cubic.sys.modular.buyrelation.enums.BuyRelationExceptionEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 购买关系表 服务实现类
 */
@Service
public class BuyRelationServiceImpl extends ServiceImpl<BuyRelationMapper, BuyRelation> implements BuyRelationService {

    @Override
    public PageResult<BuyRelation> page(BuyRelationParam buyRelationParam) {

        // 构造条件
        LambdaQueryWrapper<BuyRelation> queryWrapper = new LambdaQueryWrapper<>();

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<BuyRelation> list(BuyRelationParam buyRelationParam) {

        // 构造条件
        LambdaQueryWrapper<BuyRelation> queryWrapper = new LambdaQueryWrapper<>();

        return this.list(queryWrapper);
    }

    @Override
    public void add(BuyRelationParam buyRelationParam) {

        // 将dto转为实体
        BuyRelation buyRelation = new BuyRelation();
        BeanUtil.copyProperties(buyRelationParam, buyRelation);

        this.save(buyRelation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(BuyRelationParam buyRelationParam) {
        this.removeById(buyRelationParam.getId());
    }

    @Override
    public void edit(BuyRelationParam buyRelationParam) {

        // 根据id查询实体
        BuyRelation buyRelation = this.queryBuyRelation(buyRelationParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(buyRelationParam, buyRelation);

        this.updateById(buyRelation);
    }

    @Override
    public BuyRelation detail(BuyRelationParam buyRelationParam) {
        return this.queryBuyRelation(buyRelationParam);
    }



    /**
     * 获取购买关系表
     */
    private BuyRelation queryBuyRelation(BuyRelationParam buyRelationParam) {
        BuyRelation buyRelation = this.getById(buyRelationParam.getId());
        if (ObjectUtil.isEmpty(buyRelation)) {
            throw new ServiceException(BuyRelationExceptionEnum.NOT_EXISTED);
        }
        return buyRelation;
    }
}